package allod.gui.som

import swing._
import allod.som.{Lattice, LabeledLattice}
import allod.som.LabeledLattice.Marker
import allod.gui.MigPanel
import allod.som.upgma.Cluster

/**
 * Created by IntelliJ IDEA.
 * User: allod
 * Date: 10 січ 2010
 * Time: 0:03:30
 */

class LatticeVisualizer(private var labeledLattice: LabeledLattice[Label]) extends BorderPanel {
  def getLabeledLattice() = labeledLattice
  updateLattice(labeledLattice)
  reactions += {
    case DendrogramEvent(clusters: Seq[Cluster]) =>
      val marker = new Marker[Label](labeledLattice.peer)
      labeledLattice = marker.createLabeledLattice(clusters, LabeledLattice.clusterLabelCreator(clusters)(_))
      updateLattice(labeledLattice)
  }

  def this(lattice: Lattice, dendrogram: Dendrogram) {
    this ({
      val marker = new Marker[Label](lattice)
      val clusters = dendrogram.getSelectedClusters
      marker.createLabeledLattice(clusters, LabeledLattice.clusterLabelCreator(clusters)(_))
    })
    listenTo(dendrogram)
  }

  private def updateLattice(labeledLattice: LabeledLattice[Label]) {
    peer.removeAll()
    val resultMap = new MigPanel("insets 0, fill, gap 1px 1px, wrap " + labeledLattice.columns)
    add(resultMap, BorderPanel.Position.Center)
    for{
      column <- 0 until labeledLattice.columns
      row <- 0 until labeledLattice.rows
    } resultMap.add(labeledLattice.labelAt(column, row), "grow, growx")
    resultMap.revalidate
  }
}